﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

using SB.Logging;
using SB.Tools;
using SB.UserSettings;

namespace SB.CustomControlLibrary
{
    public partial class UserDataGridView : DataGridView
    {
        private static readonly ILogger log = LoggingFacade.GetLogger(typeof(UserDataGridView));
        private bool sortedDescending = false;

        private Type entityType = typeof(object);

        private string _UniqueDatagridName;
        public string UniqueDatagridName
        {
            set
            {
                _UniqueDatagridName = value;
            }
            get
            {
                return _UniqueDatagridName;
            }
        }

        public UserDataGridView()
        {
            InitializeComponent();
            InitializeContextMenu();

            SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            ColumnHeaderMouseClick += new DataGridViewCellMouseEventHandler(TicketLineDatagrid_ColumnHeaderMouseClick);
            ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.StandardTab = true;
        }

        private void InitializeContextMenu()
        {
            ContextMenu cm = new ContextMenu();
            
            MenuItem miAnpassen = new MenuItem("Ansicht anpassen");
            MenuItem miReset = new MenuItem("Ansicht zurücksetzen");
            
            miAnpassen.Click += new EventHandler(miAnpassen_Click);
            miReset.Click += new EventHandler(miReset_Click);
            
            cm.MenuItems.Add(miAnpassen);
            cm.MenuItems.Add(miReset);

            ContextMenu = cm;
        }

        void miAnpassen_Click(object sender, EventArgs e)
        {
            if (_UniqueDatagridName == null)
                throw new Exception("Bitte dem Datagrid noch über UniqueDatagridName=\"...\"; einen Namen zuweisen!");
            new UserDataGridViewCustomize(UniqueDatagridName, entityType).ShowDialog();
            Prepare();
        }

        void miReset_Click(object sender, EventArgs e)
        {
            if (_UniqueDatagridName == null)
                throw new Exception("Bitte dem Datagrid noch über UniqueDatagridName=\"...\"; einen Namen zuweisen!");
            UserDataGridViewCustomize.ResetColumns(entityType, UniqueDatagridName);
            Prepare();
        }



        public bool IsSelected
        {
            get
            {
                return SelectedRows.Count > 0;
            }
        }

        public T GetSelectedItem<T>()
        {
            if (SelectedRows.Count > 0)
            {
                return ((SortableBindingList<T>)DataSource)[SelectedRows[0].Index];
            }
            else
            {
                return default(T);
            }
        }

        protected override void OnDataSourceChanged(EventArgs e)
        {
            base.OnDataSourceChanged(e);
        }

        protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
        {
            base.OnDataBindingComplete(e);
            AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
            if (DataSource.GetType().Name != typeof(SortableBindingList<object>).Name)
                throw new Exception("Als DataSource für das TicketLineDatagrid dürfen nur SortableBindingLists verwendet werden (siehe SEPM.SR).");

            Prepare();

            // Nur mit TAB erreichbar, wenn Daten vorhanden sind
            TabStop = Rows.Count > 0;
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);

            if (e.Button == MouseButtons.Right)
            {
                ContextMenu.Show(this, e.Location);
            }
        }

        protected void Prepare()
        {
            try
            {
                Type[] types = DataSource.GetType().GetGenericArguments();

                if (types.Length != 1)
                    throw new Exception("The DataSource List needs a generic type argument!");

                entityType = types[0];

                SortableBindingList<UserSetting> list = UserSettingsFacade.XMLInterface.ReadUserSettings("UserDataGridViews", UniqueDatagridName);
                //TLCommons.ReadDatagridColumnsFromXML(ref list, UniqueDatagridName);

                if (list.Count == 0)
                    UserDataGridViewCustomize.ResetColumns(entityType, UniqueDatagridName);

                foreach (DataGridViewColumn col in Columns)
                {
                    col.Visible = false;
                }

                int index = 0;
                foreach (UserSetting s in list)
                {
                    Columns[s.Name].Visible = true;
                    Columns[s.Name].DisplayIndex = index;
                    Columns[s.Name].HeaderText = s.Text;
                    index++;
                }
            }
            catch { }
        }

        protected void TicketLineDatagrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridViewColumn selectedColumn = Columns[e.ColumnIndex];

            if (selectedColumn.SortMode != DataGridViewColumnSortMode.NotSortable)
            {

                ListSortDirection direction;

                if (sortedDescending == false)
                {
                    direction = ListSortDirection.Descending;
                    sortedDescending = true;
                }
                else
                {
                    direction = ListSortDirection.Ascending;
                    sortedDescending = false;
                }

                Sort(selectedColumn, direction);

                selectedColumn.HeaderCell.SortGlyphDirection =
                direction == ListSortDirection.Ascending ?
                SortOrder.Ascending : SortOrder.Descending;
            }
        }
    }
}
